/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MantenimientoUsuarios.java
 *
 * Created on 05-jun-2012, 2:03:04
 */
package Interfaz_Grafica;

import Logica.LPersonas;
import Logica.LUsuario;
import Objetos.Usuario;
import java.awt.Component;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Omar Heráclides
 */
public class MantenimientoUsuarios extends javax.swing.JFrame {

    String MensajeValidacion;
    String CodigoUsuario;
    Boolean Modificable;

    public String getCodigoUsuario() {
        return CodigoUsuario;
    }

    public void setCodigoUsuario(String CodigoUsuario) {
        this.CodigoUsuario = CodigoUsuario;
    }

    public Boolean getModificable() {
        return Modificable;
    }

    public void setModificable(Boolean Modificable) {
        this.Modificable = Modificable;
    }

    public String getMensajeValidacion() {
        return MensajeValidacion;
    }

    public void setMensajeValidacion(String MensajeValidacion) {
        this.MensajeValidacion = MensajeValidacion;
    }

    /** Creates new form MantenimientoUsuarios */
    public MantenimientoUsuarios() throws SQLException {
        this.setTitle("Mantenimiento de Usuarios");
        initComponents();
        CargarROL();
        CargarDNI();

// Evita que el Frame padre obtenga el foco 
        setModificable(false);
        DefaultTableModel dtm = new DefaultTableModel();
        String titulos[] = {"Nombre de Usuario", "Contraseña", "Rol"};
        dtm.setColumnIdentifiers(titulos);
        dtmTablaUsuario.setModel(dtm);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtContraseña = new java.awt.TextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        textField3 = new java.awt.TextField();
        jButton4 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        dtmTablaUsuario = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        txtUsuario = new java.awt.TextField();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jcbRol = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jcbUsuarioDNI = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel2.setText("Contraseña Usuario:");

        jLabel1.setText("Nombre Usuario:");

        jButton4.setText("Buscar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        dtmTablaUsuario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        dtmTablaUsuario.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                dtmTablaUsuarioMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(dtmTablaUsuario);

        jButton3.setText("Limpiar");

        jButton2.setText("Modificar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setText("Agregar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setText("ROL: ");

        jLabel5.setText("Personal DNI: ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton4)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel2)
                                .addComponent(jLabel1)
                                .addComponent(jLabel3)
                                .addComponent(jLabel4)
                                .addComponent(jLabel5))
                            .addGap(38, 38, 38)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(textField3, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jcbUsuarioDNI, 0, 96, Short.MAX_VALUE)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                            .addComponent(txtContraseña, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
                                            .addComponent(txtUsuario, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
                                            .addComponent(jcbRol, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                    .addGap(48, 48, 48)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jButton1)
                                        .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
                .addGap(10, 10, 10))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(11, 11, 11)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton3))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtContraseña, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addGap(6, 6, 6)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jcbRol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addGap(9, 9, 9)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jcbUsuarioDNI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel5)))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton4)
                    .addComponent(textField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(25, 25, 25)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(21, 21, 21))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
    int resp;
    Boolean validPage = true;
    validPage = ValidarPagina();

    resp = JOptionPane.showConfirmDialog(null, "¿Desea Agregar un usuario?", "Pregunta", 0);
    if (validPage) {
        if (resp == 0) {
            try {
                LimpiarTabla();
                Usuario objUsuario = new Usuario();
                objUsuario.setContraseña(this.txtContraseña.getText());
                objUsuario.setNombreUsuario(this.txtUsuario.getText());
                objUsuario.setIdPersona(ObtenerIdPersona(this.jcbUsuarioDNI.getSelectedItem().toString()));
                objUsuario.setEstado(1);
                objUsuario.setRol(this.jcbRol.getSelectedItem().toString());
                this.limpiar();
                LUsuario objLUsuario = new LUsuario();
                String mensaje = "Fallo";
                mensaje = objLUsuario.AgregarUsuario(objUsuario);
                JOptionPane.showMessageDialog(null, mensaje,
                        "Información", JOptionPane.INFORMATION_MESSAGE);
            } catch (SQLException ex) {
                Logger.getLogger(MantenimientoUsuarios.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    } else {
        JOptionPane.showMessageDialog(null, this.getMensajeValidacion(),
                "Información", JOptionPane.INFORMATION_MESSAGE);
    }

}//GEN-LAST:event_jButton1ActionPerformed

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
    int resp;
    if (this.Modificable == true) {
        resp = JOptionPane.showConfirmDialog(null, "¿Desea Modificar el usuario?", "Pregunta", 0);
        if (resp == 0) {
            try {
                LimpiarTabla();
                Usuario objUsuario = new Usuario();
                objUsuario.setIdUsuario(this.getCodigoUsuario());
                objUsuario.setContraseña(this.txtContraseña.getText());
                objUsuario.setNombreUsuario(this.txtUsuario.getText());
                objUsuario.setIdPersona(ObtenerIdPersona(this.jcbUsuarioDNI.getSelectedItem().toString()));
                objUsuario.setEstado(1);
                objUsuario.setRol(this.jcbRol.getSelectedItem().toString());
                this.limpiar();
                LUsuario objLUsuario = new LUsuario();
                String mensaje = "Fallo";
                mensaje = objLUsuario.ModificarUsuario(objUsuario);
                JOptionPane.showMessageDialog(null, mensaje,
                        "Información", JOptionPane.INFORMATION_MESSAGE);
            } catch (SQLException ex) {
                Logger.getLogger(MantenimientoUsuarios.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        this.setModificable(false);
        this.limpiar();
    } else {
        JOptionPane.showMessageDialog(null, "Debe selecionar un registro de la tabla!", "Información", JOptionPane.INFORMATION_MESSAGE);
    }
}//GEN-LAST:event_jButton2ActionPerformed

private void dtmTablaUsuarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dtmTablaUsuarioMouseClicked
// TODO add your handling code here:
    int row = this.dtmTablaUsuario.rowAtPoint(evt.getPoint());
    if (row >= 0) {
        this.setModificable(true);
        //String titulos[] = {"Codigo", "Nombre", "Ap. Paterno", "Ap. Materno", "DNI", "Fecha Nacimiento", "Sexo"};
        this.txtUsuario.setText(this.dtmTablaUsuario.getModel().getValueAt(row, 1).toString());
        this.txtContraseña.setText(this.dtmTablaUsuario.getModel().getValueAt(row, 2).toString());

        this.jcbRol.setSelectedItem(this.dtmTablaUsuario.getModel().getValueAt(row, 3).toString());
        this.setCodigoUsuario(this.dtmTablaUsuario.getModel().getValueAt(row, 0).toString());
    } else {
        this.setModificable(false);
    }

}//GEN-LAST:event_dtmTablaUsuarioMouseClicked

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    try {
        // TODO add your handling code here:
        LUsuario objLUsuario = new LUsuario();
        this.dtmTablaUsuario.setModel(objLUsuario.MostrarDatos());
    } catch (SQLException ex) {
        Logger.getLogger(MantenimientoUsuarios.class.getName()).log(Level.SEVERE, null, ex);
    }

}//GEN-LAST:event_jButton4ActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable dtmTablaUsuario;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox jcbRol;
    private javax.swing.JComboBox jcbUsuarioDNI;
    private java.awt.TextField textField3;
    private java.awt.TextField txtContraseña;
    private java.awt.TextField txtUsuario;
    // End of variables declaration//GEN-END:variables

    private void CargarROL() throws SQLException {
        LUsuario objLUsuario = new LUsuario();
        ArrayList<String> arr = new ArrayList();
        arr = objLUsuario.ObtenerROL();
        for (int i = 0; i < arr.size(); i++) {
            this.jcbRol.addItem(arr.get(i).toString());
        }
    }

    private void CargarDNI() throws SQLException {
        LPersonas objLPersonas = new LPersonas();
        ArrayList<String> arr = new ArrayList();
        arr = objLPersonas.ObtenerDNI();
        for (int i = 0; i < arr.size(); i++) {
            this.jcbUsuarioDNI.addItem(arr.get(i).toString());
        }
    }

    private Boolean ValidarPagina() {
        return true;
    }

    private void LimpiarTabla() {
        DefaultTableModel dtm = new DefaultTableModel();
        String titulos[] = {"Nombre de Usuario", "Contraseña", "Rol"};
        dtm.setColumnIdentifiers(titulos);
        Object datos[] = new Object[3];
        dtm.addRow(datos);
        dtmTablaUsuario.setModel(dtm);
    }

    private void limpiar() {
        this.txtContraseña.setText("");
        this.txtUsuario.setText("");


    }

    private String ObtenerIdPersona(String dni) throws SQLException {
        LUsuario objLUsuario = new LUsuario();
        return objLUsuario.ObtenerDNI(dni);
    }
}
